package com.notice.pomo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;

import com.notice.entity.Constants;
import com.notice.entity.Debug;
import com.notice.entity.Utils;
import com.notice.preference.Preferences;
import com.notice.timer.PomodoroPreset;
import com.notice.timer.PomodoroService;
import com.notice.timer.PomodoroTimer;
import com.notice.timer.PomodoroTimerCallback;

public class PomoActivity extends Activity {
	
	private PomodoroService.PomoBinder serviceBinder;
	private boolean mIsBound;
	private PomodoroPreset preset;
	private static final String TAG = "pomo";
	//wakelock
    private PowerManager.WakeLock wakeLock;
	
	private ServiceConnection mConnection = new ServiceConnection (){

		@Override
		public void onServiceConnected (ComponentName name, IBinder service){
			serviceBinder = ((PomodoroService.PomoBinder)service);
			mIsBound = true;
			
			serviceBinder.setPreset(preset);
			serviceBinder.start();
			PomodoroTimer timer = serviceBinder.getTimer();
			timer.attachCallback(new TimerCallback());

		}

		@Override
		public void onServiceDisconnected (ComponentName name){}
	};
	
	private TextView timerDisplay;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setUpViews();
        preset = PomodoroPreset.createDefault(getApplicationContext());
        Preferences.reloadPreferences(this);
      //grab wake lock
      		wakeLock = ((PowerManager)getSystemService(Context.POWER_SERVICE))
      					.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "pomo");
    }
    
    @Override
	protected void onStart() {
		super.onStart();
		doBindService();
		if(Preferences.isWakeLockEnabled() && !wakeLock.isHeld()){
			wakeLock.acquire();
			Debug.d(TAG, "Wake lock acquired.");
		}else if(wakeLock.isHeld()){
			wakeLock.release();
			Debug.d(TAG, "Wake lock released.");
		}
		//recheck for silent
		//ignore keyguard
		Window win = getWindow();
		win.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		win.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
	}

	@Override
	protected void onStop() {
		super.onStop();
		if(wakeLock.isHeld()){
			wakeLock.release();
			Debug.d(TAG, "Wake lock released.");
		}
		
	}

	
	@Override
	public void onBackPressed() {
		confirmCancel(true);
	}

	private void confirmCancel(boolean showDialog){
		if(showDialog){
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			dialog.setIcon(android.R.drawable.ic_dialog_alert);
			dialog.setTitle(R.string.dialog_cancel_title);
			dialog.setMessage(R.string.dialog_cancel_message);
			dialog.setPositiveButton(R.string.button_yes, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					serviceBinder.cancel();
					doUnbindService();
					finish();
				}
			});
			dialog.setNegativeButton(R.string.button_no, null);
			dialog.show();
		} else{
			serviceBinder.cancel();
			doUnbindService();
			finish();
		}
	}
	private void setUpViews() {
		timerDisplay = (TextView) findViewById(R.id.tv_time);
	}

	public void setTimerDisplay(int hours, int minutes, int seconds){
		timerDisplay.setText(Utils.valueToString(minutes)+":"+Utils.valueToString(seconds));
	}
	
	private void doBindService() {
		Intent i = new Intent(this, PomodoroService.class);
		boolean result = bindService(i, mConnection, Context.BIND_AUTO_CREATE);
		Log.v(TAG, result+"*****");
	}

	private void doUnbindService() {
		if (mIsBound) {       
			unbindService(mConnection);
			mIsBound = false;
		}
	}

	public PomodoroService.PomoBinder getServiceBinder() {
		return serviceBinder;
	}

    private class TimerCallback implements PomodoroTimerCallback{

		@Override
		public void onTimerStateChanged(PomodoroTimer timer) {
			switch(timer.getState()){
			case WORK:
//				if(nextPreset != null){//restart pomodoro timer with new preset
//					Intent i = new Intent(TimerActivity.this, TimerActivity.class);
//					i.putExtra(Constants.KEY_POMODORO_PRESET, nextPreset);
//					confirmCancel(false);
//					startActivity(i);
//				}
//				presetState.setText("");
//				nextPresetLabel.setVisibility(View.INVISIBLE);
//				nextDropdown.setVisibility(View.INVISIBLE);
				break;
			case BREAK:
//				presetState.setText(getString(R.string.pomodoro_break));
//				nextPresetLabel.setVisibility(View.VISIBLE);
//				nextDropdown.setVisibility(View.VISIBLE);
				break;
			case EX_BREAK:
//				presetState.setText(getString(R.string.pomodoro_ex_break));
//				nextPresetLabel.setVisibility(View.VISIBLE);
//				nextDropdown.setVisibility(View.VISIBLE);
				break;
			}
		}

		@Override
		public void onStart(PomodoroTimer timer) {

		}

		@Override
		public void onPause(PomodoroTimer timer) {

		}

		@Override
		public void onResume(PomodoroTimer timer) {

		}

		@Override
		public void onCancel(PomodoroTimer timer) {

		}

		@Override
		public void onTimerTicked(PomodoroTimer timer) {
			setTimerDisplay(timer.getHoursRemaining(), timer.getMinutesRemaining(), timer.getSecondsRemaining());
		}


	}
}